package com.roc.web.action.terminal;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.opensymphony.xwork2.ActionContext;
import com.roc.bean.TermBean;
import com.roc.newPage.IPageService;
import com.roc.page.BaseSearchCondition;
import com.roc.page.PaginationBaseAction;
import com.roc.pojo.Estidinfo;
import com.roc.pojo.ModuleCategory;
import com.roc.pojo.Operators;
import com.roc.pojo.MerchantModuleRight;
import com.roc.pojo.Module;
import com.roc.pojo.OrgBean;
import com.roc.pojo.TblDictionaryItem;
import com.roc.pojo.TblInsInf;
import com.roc.pojo.Termapply;
import com.roc.service.IMerchantServices;
import com.roc.service.IPagenitionService;
import com.roc.service.ITerminalService;
import com.roc.service.IorgService;
import com.roc.service.ServiceException;
import com.roc.service.operator.IPowerInfoService;
import com.roc.util.Constance;
import com.roc.util.constant.ConfigMerinfoUtil;
import com.roc.util.constant.ConfigProperties;
import com.roc.util.constant.ConfigPropertiesUtils;
import com.roc.util.constant.Constant;
import com.roc.util.constant.OperatorsStatus;
import com.roc.util.constant.Role;
import com.roc.util.constant.SexStatus;
import com.roc.util.constant.Terminal;
import com.roc.util.constant.TerminalFlag;

/**
 * 
 * @author 陈锴
 * 
 * 终端序列号添加  终端查询
 * 
 * 2014-08-18
 *
 */

@Component
@Scope("prototype")
@Namespace("/terminalList")
public class TerminalListAction extends PaginationBaseAction{
	
	private Logger logger=LogManager.getLogger(TerminalListAction.class);
	
	private TerminalListSearchCondition searchCondition;
	
	private Termapply termapply;
	
	private String msg;
	
	private List<TermBean> termBeanList;
	
	private List<TblInsInf> orgList=new ArrayList<TblInsInf>();
	
	@Autowired
	IorgService orgService;
	
	@Autowired
	IPageService pagenitionService;
	
	@Autowired
	ITerminalService terminalService;
	
	@Autowired 
	IMerchantServices merchantServices;
	
	@Autowired
	IPowerInfoService powerInfoService;
	private String queryFlag;//终端冻结解冻查询标识
	
	/**
	 * 终端管理初始化页面
	 * @return
	 * @throws Exception
	 */
	@Action(value = "queryTerminalJsp", results = { @Result(name = "success", location = "/pages/terminal/terminal_list.jsp")
             })
	public String queryTerminalJspAction() throws Exception{		
		org();		
		return SUCCESS;
	}

	
	/**
     * 终端解冻冻结查询初始化
     */
	@Action(value = "queryTerminalFreezeJsp", results = { @Result(name = "success", location = "/pages/terminal/terminal_freeze_or_unfreeze.jsp")
    })
	public String queryTerminalFreezeJsp() throws Exception{
	   org();
	   return SUCCESS;
	}
	
	/**
	 * 终端管理查询
	 * @return
	 * @throws Exception
	 */
	@Action(value = "queryTerminalSN", results = { @Result(name = "success", location = "/pages/terminal/terminal_list.jsp"),
			@Result(name = "toTerminalQuery", location = "/pages/terminal/terminal_freeze_or_unfreeze.jsp"),
           })
	//查询终端
	public String queryTerminalSNAction() throws Exception{
		msg=null;
        Operators logingMerchant=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		
		if(searchCondition==null){
			searchCondition=(TerminalListSearchCondition)getSearchConditionFromSession();
			if(searchCondition==null){
				searchCondition=new TerminalListSearchCondition();
			}
		}
		try {
			
			org();			
			Map<String, String> map=powerInfoService.queryRealIdByOpId(logingMerchant.getSuperiorId(), logingMerchant.getRoleType(), logingMerchant.getId(), logingMerchant.getOrgCode());
	        String superRole= map.get("superRole");
	        String opRealId =map.get("opRealId");
	        searchCondition.setGroupCd(map.get("groupCd"));
	        searchCondition.setRoleType(superRole);// 角色
	        searchCondition.setOpId(opRealId);//当前人员id
	        searchCondition.setOneOrgCode(logingMerchant.getOneagentid());//机构
	        if(superRole.equals(Role.O_MANAGER.getCode())){//若是直营机构
	        	Operators manOperators=powerInfoService.findDirectlyUnder(Long.valueOf(opRealId));
	        	if(manOperators!=null){
	        		searchCondition.setDirect("exist");
	        	}
	        }
			int rows=pagenitionService.countSQL(searchCondition);
			searchRsList=pagenitionService.findAllSQL(searchCondition, calcuStart(getCurrentPage()), Constance.PAGE_MAX_SIZE);
			Pattern p=Pattern.compile("YJ[0-9]*");//验证是否绑定标志
			List<Estidinfo> estidList= new ArrayList<Estidinfo>();
			if(searchRsList!=null&&searchRsList.size()>0){
				Iterator iterator=searchRsList.iterator();
				while (iterator.hasNext()) {
					Object[] obj= (Object[])iterator.next();
					Estidinfo est=new Estidinfo(); 
					for(TblInsInf bean:orgList){
						if(Constance.Null2EmptyTrim(obj[0]).equals(bean.getInsIdCd())){
							est.setOrgCode(bean.getInsName());
						}
					}
					est.setMid(Constance.Null2EmptyTrim(obj[1]));
					est.setMidName(Constance.Null2EmptyTrim(obj[2]));
					est.setTidName(Constance.Null2EmptyTrim(obj[3]));
					est.setTerTid(Constance.Null2EmptyTrim(obj[4]));
					est.setTidKind(ConfigMerinfoUtil.getPosType(Constance.Null2EmptyTrim(obj[5])));
					est.setFlagName(TerminalFlag.valueOfCode(Constance.Null2EmptyTrim(obj[6])).getName());
					est.setFlag(Constance.Null2EmptyTrim(obj[6]));
					est.setSerialNum(Constance.Null2EmptyTrim(obj[7]));					
					if(!Pattern.matches("YJ[0-9]*",est.getSerialNum())){
						est.setStatus("Y");
					}else{
						est.setStatus("N");
					}					
					estidList.add(est);
				}
			}
			searchRsList.clear();
			searchRsList.addAll(estidList);			
			this.setTotalPage(this.calcuTotalPage(rows));
			getRequest().setAttribute(SEARCH_RS_LIST, searchRsList);
			getRequest().setAttribute(CURRENT_PAGE, this.getCurrentPage());
			getRequest().setAttribute(TOTAOL_PAGE, this.getTotalPage());
			setSearchToConditionSession(searchCondition);
			
		} catch (ServiceException e) {
			
			logger.error(e.getMessage(),e);
			addActionError(e.getMessage());
			
		}
		
		if("1".equals(queryFlag)){
			return "toTerminalQuery";
		}
	
		
		return SUCCESS;
	}
	
	//查询机构
	public void org() throws Exception{
		Operators logingMerchant=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		TblInsInf infs=orgService.queryOrgByOrgCode(logingMerchant.getOrgCode());
		orgList.add(infs);
		/*if(Role.SYSTEM.getCode().equals(logingMerchant.getRoleType())){
			TblInsInf inf = new TblInsInf();
			inf.setInsIdCd("");
			inf.setInsName("--请选择机构--");
			orgList.add(inf);
			List<TblInsInf> list=orgService.queryOrgList();
			orgList.addAll(list);
		}else{
			TblInsInf infs=orgService.queryOrgByOrgCode(logingMerchant.getOrgCode());
			orgList.add(infs);
		}*/			
	}
	
	protected void orgTheListSpecially(List<Estidinfo> estidList) {
    	List<Object> tempList=new ArrayList<Object>();
		for(Object obj:estidList){
			Estidinfo temp=(Estidinfo)obj;
			/*for(TblInsInf bean:orgList){
				if(temp.getOrgCode().equals(bean.getInsIdCd())){
					temp.setOrgCode(bean.getInsName());
				}
			}*/
			
			tempList.add(temp);
		}
		searchRsList=tempList;
	}
	
	@Override
	protected String getInitPageSize() {
		// TODO Auto-generated method stub
		return Constance.PAGE_MAX_SIZE+"";
	}

	/* (non-Javadoc)
	 * @see com.roc.page.PaginationBaseAction#getSearchConditionFromSession()
	 */
	@Override
	protected BaseSearchCondition getSearchConditionFromSession() {
		// TODO Auto-generated method stub
		return (TerminalListSearchCondition)getSession().getAttribute(SEARCH_SESSION_BEAN_TERMINAL_LIST);
	}

	/* (non-Javadoc)
	 * @see com.roc.page.PaginationBaseAction#getSearchConditionFromSubClass()
	 */
	@Override
	protected BaseSearchCondition getSearchConditionFromSubClass()
			throws Exception {
		// TODO Auto-generated method stub
		return searchCondition;
	}

	/* (non-Javadoc)
	 * @see com.roc.page.PaginationBaseAction#setSearchConditionToSubClass(com.roc.page.BaseSearchCondition)
	 */
	@Override
	protected void setSearchConditionToSubClass(
			BaseSearchCondition searchCondition) throws Exception {
		this.setSearchConditionToSubClass(searchCondition);
	}

	/* (non-Javadoc)
	 * @see com.roc.page.PaginationBaseAction#setSearchToConditionSession(com.roc.page.BaseSearchCondition)
	 */
	@Override
	protected void setSearchToConditionSession(
			BaseSearchCondition searchCondition) {
		getSession().setAttribute(SEARCH_SESSION_BEAN_TERMINAL_LIST, searchCondition);
	}

	public TerminalListSearchCondition getSearchCondition() {
		return searchCondition;
	}

	public void setSearchCondition(TerminalListSearchCondition searchCondition) {
		this.searchCondition = searchCondition;
	}
	
	public Termapply getTermapply() {
		return termapply;
	}

	public void setTermapply(Termapply termapply) {
		this.termapply = termapply;
	}

	public String getMsg() {
		return msg;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}

	public List<TermBean> getTermBeanList() {
		return termBeanList;
	}

	public void setTermBeanList(List<TermBean> termBeanList) {
		this.termBeanList = termBeanList;
	}

	


	public List<TblInsInf> getOrgList() {
		return orgList;
	}


	public void setOrgList(List<TblInsInf> orgList) {
		this.orgList = orgList;
	}


	public String getQueryFlag() {
		return queryFlag;
	}


	public void setQueryFlag(String queryFlag) {
		this.queryFlag = queryFlag;
	}
	
}
